<?php
/**
 * Created by 豆豆.
 * User: longrbl@163.com
 * Date: 2016/9/13
 * Time: 1:13
 * 模板
 */

namespace style\lib;

class Ctlr
{
  public $request;
  public $response;
  public $service;

  function __construct($request, $response, $service)
  {
    $this->request = $request;
    $this->response = $response;
    $this->service = $service;
  }

  /**
   * @param $tpl 模板名称
   * @param array $data 模板里面使用的数据
   * @throws \Exception
   */
  function view($tpl, $data = [])
  {
    $this->response->header("Content-Type", "text/html; charset=utf-8");
    if (!empty($data)) {
      extract($data);
    }
    $path_p = $this->request->model . '/view/' . $tpl;
    if (is_file($path_p)) {
      try {
        ob_start();
        include $path_p;
        $vime = ob_get_clean();
        $this->response->end($vime);//像浏览器输出数据
      } catch (\Exception $e) {
        throw new \Exception('模板错误');
      }
    } else {
      $this->response->end('模板错误');
    }
  }

  /**
   * @param $data 要返回的数据 json|array
   * @param bool $type $data是否是josn
   */
  function json($data, $type = true)
  {
    $this->response->header("Content-Type", "application/json; charset=utf-8");
    if ($type) {
      $this->response->end($data);
    } else {
      $this->response->end(json_encode($data));
    }
    $this->request = null;
    $this->response = null;
    return;
  }

  /**
   * @param $data 要处理的数据 array
   * @return mixed 阻塞投递异步任务到task进程 返回json数据格式
   */
  function taskwait($data)
  {
    return $this->service->taskwait(json_encode($data));
  }

  /**
   * @param $data要处理的数据 array
   * @return mixed 投递异步任务到task进程 返回json数据格式
   */
  function task($data)
  {
    return $this->service->task(json_encode($data));
  }

}